const express = require('express')
const app = express()
const fs = require('fs')
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
let shopcart = require('./shop-cart.json')
//获得购物车商品数据
app.get('/shopcart', (req, res) => {
  let token = req.get('token')
  console.log(token)
  res.send(shopcart)
})
//改变购物车商品数量
app.all('/shopcart/changecount/:id', (req, res) => {
  try {
    // let {id} = req.params
    // let {type} = req.body
    let id = "002"
    let type = "decrement"
    let newShopcart = []
    if (type == "increment") {
      newShopcart = shopcart.map(item => {
        if (id == item.id) {
          item.count++
        }
        return item
      })
    } else if (type == 'decrement') {
      newShopcart = shopcart.map(item => {
        if (id === item.id) {
          if (item.count - 1 < 1) {
            res.send({ code: 400, message: "更改json失败" })
          } else {
            item.count--
          }
        }
        return item
      })
    }
    fs.writeFileSync("./shop-cart.json", JSON.stringify(newShopcart))
    res.send({ code: 200, message: "更改json成功" })
  } catch (e) {
    res.send({ code: 400, message: '更改json失败' })
  }
})
//删除购物车商品
app.get('/shopcarts/:id', (req, res) => {
  try {
    let { id } = req.params
    let index = 0
    let shopCartobj = shopcart.find((item,i) => {
      index = i
      return item.id == id
    })
    shopcart.splice(index,1)
    res.send({code: 200,message: "删除购物车商品成功"})
  } catch (e) {
    res.send({code: 400,message: "删除购物车商品失误"})
  }
})
//添加购物车商品
app.post('/shopcarts',(req,res) => {
  try {
    let length = shopcart.length
    
  }catch(e) {

  }
})
app.listen(3000, () => {
  console.log('服务已经启动3000端口')
})